<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>RBAC管理系统</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
    <nav class="navbar navbar-expand-lg navbar-dark bg-dark">
        <div class="container">
            <a class="navbar-brand" href="#">RBAC管理系统</a>
            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav">
                <span class="navbar-toggler-icon"></span>
            </button>
            <div class="collapse navbar-collapse" id="navbarNav">
                <ul class="navbar-nav me-auto">
                    <li class="nav-item">
                        <a class="nav-link" href="#" onclick="getAllUsers()">用户管理</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="#" onclick="getAllRoles()">角色管理</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="#" onclick="getAllPermissions()">权限管理</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="#" onclick="getAllPages()">页面管理</a>
                    </li>
                </ul>
                <button class="btn btn-outline-light" onclick="logout()">退出登录</button>
            </div>
        </div>
    </nav>

    <div class="container mt-4">
        <div id="content">
            <h2>欢迎使用RBAC管理系统</h2>
            <p>请点击上方导航栏选择要管理的内容。</p>
        </div>
    </div>

    <!-- 编辑用户模态框 -->
    <div class="modal fade" id="editUserModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">编辑用户</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <form id="editUserForm">
                        <input type="hidden" id="editUserId">
                        <div class="mb-3">
                            <label for="editUsername" class="form-label">用户名</label>
                            <input type="text" class="form-control" id="editUsername" required>
                        </div>
                        <div class="mb-3">
                            <label for="editEmail" class="form-label">邮箱</label>
                            <input type="email" class="form-control" id="editEmail">
                        </div>
                        <div class="mb-3">
                            <label for="editPassword" class="form-label">密码（留空表示不修改）</label>
                            <input type="password" class="form-control" id="editPassword">
                        </div>
                        <div class="mb-3">
                            <label class="form-label">角色</label>
                            <div id="editUserRoles" class="border p-2 rounded">
                                <!-- 角色复选框将通过JavaScript动态添加 -->
                            </div>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" onclick="saveUser()">保存</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 编辑角色模态框 -->
    <div class="modal fade" id="editRoleModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">编辑角色</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <form id="editRoleForm">
                        <input type="hidden" id="editRoleId">
                        <div class="mb-3">
                            <label for="editRoleName" class="form-label">角色名称</label>
                            <input type="text" class="form-control" id="editRoleName" required>
                        </div>
                        <div class="mb-3">
                            <label for="editRoleDescription" class="form-label">描述</label>
                            <input type="text" class="form-control" id="editRoleDescription">
                        </div>
                        <div class="mb-3">
                            <label class="form-label">权限</label>
                            <div id="editRolePermissions" class="border p-2 rounded">
                                <!-- 权限复选框将通过JavaScript动态添加 -->
                            </div>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" onclick="saveRole()">保存</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 编辑权限模态框 -->
    <div class="modal fade" id="editPermissionModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">编辑权限</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <form id="editPermissionForm">
                        <input type="hidden" id="editPermissionId">
                        <div class="mb-3">
                            <label for="editPermissionName" class="form-label">权限名称</label>
                            <input type="text" class="form-control" id="editPermissionName" required>
                        </div>
                        <div class="mb-3">
                            <label for="editPermissionDescription" class="form-label">描述</label>
                            <input type="text" class="form-control" id="editPermissionDescription">
                        </div>
                        <div class="mb-3">
                            <label for="editPermissionResource" class="form-label">资源路径</label>
                            <input type="text" class="form-control" id="editPermissionResource" required>
                        </div>
                        <div class="mb-3">
                            <label for="editPermissionAction" class="form-label">操作类型</label>
                            <select class="form-control" id="editPermissionAction" required>
                                <option value="GET">GET</option>
                                <option value="POST">POST</option>
                                <option value="PUT">PUT</option>
                                <option value="DELETE">DELETE</option>
                            </select>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" onclick="savePermission()">保存</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 编辑页面模态框 -->
    <div class="modal fade" id="editPageModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">编辑页面</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <form id="editPageForm">
                        <input type="hidden" id="editPageId">
                        <div class="mb-3">
                            <label for="editPageName" class="form-label">页面名称</label>
                            <input type="text" class="form-control" id="editPageName" required>
                        </div>
                        <div class="mb-3">
                            <label for="editPagePath" class="form-label">页面路径</label>
                            <input type="text" class="form-control" id="editPagePath" required>
                        </div>
                        <div class="mb-3">
                            <label for="editPageComponent" class="form-label">组件路径</label>
                            <input type="text" class="form-control" id="editPageComponent" required>
                        </div>
                        <div class="mb-3">
                            <label for="editPageIcon" class="form-label">图标</label>
                            <input type="text" class="form-control" id="editPageIcon">
                        </div>
                        <div class="mb-3">
                            <label for="editPageSort" class="form-label">排序</label>
                            <input type="number" class="form-control" id="editPageSort" value="0">
                        </div>
                        <div class="mb-3">
                            <label for="editPageParentId" class="form-label">父页面</label>
                            <select class="form-control" id="editPageParentId">
                                <option value="">无</option>
                            </select>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" onclick="savePage()">保存</button>
                </div>
            </div>
        </div>
    </div>

    <script>
        // 添加token检查函数
        function checkTokenStatus() {
            const token = localStorage.getItem('token');
            if (!token) {
                window.location.href = '/login';
                return;
            }

            fetch('/api/auth/check-token', {
                headers: getHeaders()
            }).catch(error => {
                console.error('Token检查失败:', error);
                handleTokenInvalid();
            });
        }

        // 处理token失效
        function handleTokenInvalid() {
            localStorage.removeItem('token');
            alert('您的登录已失效，请重新登录');
            window.location.href = '/login';
        }

        // 添加WebSocket连接
        let ws = null;
        let reconnectAttempts = 0;
        const maxReconnectAttempts = 5;
        const reconnectDelay = 5000; // 5秒

        function connectWebSocket() {
            const token = localStorage.getItem('token');
            if (!token) {
                console.log('没有token，不建立WebSocket连接');
                return;
            }

            try {
                // 使用SockJS建立连接
                const socket = new SockJS(`/ws?token=${token}`);
                ws = new Stomp.over(socket);
                
                ws.connect({}, function(frame) {
                    console.log('WebSocket连接已建立');
                    reconnectAttempts = 0; // 重置重连次数
                    
                    // 订阅个人消息
                    ws.subscribe(`/topic/user/${getCurrentUsername()}`, function(message) {
                        try {
                            const data = JSON.parse(message.body);
                            if (data.type === 'FORCE_LOGOUT') {
                                alert(data.message || '您的账号已被强制下线');
                                handleTokenInvalid();
                            }
                        } catch (error) {
                            console.error('处理WebSocket消息失败:', error);
                        }
                    });
                }, function(error) {
                    console.error('WebSocket连接失败:', error);
                    handleConnectionError();
                });
            } catch (error) {
                console.error('建立WebSocket连接失败:', error);
                handleConnectionError();
            }
        }

        // 处理连接错误
        function handleConnectionError() {
            if (reconnectAttempts < maxReconnectAttempts) {
                reconnectAttempts++;
                console.log(`尝试重连 (${reconnectAttempts}/${maxReconnectAttempts})...`);
                setTimeout(connectWebSocket, reconnectDelay);
            } else {
                console.error('WebSocket重连失败，已达到最大重试次数');
            }
        }

        // 获取当前用户名
        function getCurrentUsername() {
            const token = localStorage.getItem('token');
            if (!token) return null;
            
            try {
                const base64Url = token.split('.')[1];
                const base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
                const jsonPayload = decodeURIComponent(atob(base64).split('').map(function(c) {
                    return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
                }).join(''));
                return JSON.parse(jsonPayload).sub;
            } catch (error) {
                console.error('解析token失败:', error);
                return null;
            }
        }

        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', function() {
            // 添加SockJS和Stomp客户端库
            const sockjsScript = document.createElement('script');
            sockjsScript.src = 'https://cdn.jsdelivr.net/npm/sockjs-client@1/dist/sockjs.min.js';
            document.head.appendChild(sockjsScript);

            const stompScript = document.createElement('script');
            stompScript.src = 'https://cdn.jsdelivr.net/npm/stompjs@2.3.3/lib/stomp.min.js';
            document.head.appendChild(stompScript);

            // 等待脚本加载完成后初始化WebSocket
            sockjsScript.onload = stompScript.onload = function() {
                // 每5分钟检查一次token状态
                setInterval(checkTokenStatus, 5 * 60 * 1000);
                // 建立WebSocket连接
                connectWebSocket();
            };
        });

        // 修改现有的getHeaders函数
        function getHeaders() {
            const token = localStorage.getItem('token');
            return {
                'Authorization': `Bearer ${token}`,
                'Content-Type': 'application/json'
            };
        }

        // 获取用户列表
        async function getAllUsers() {
            try {
                const response = await fetch('/api/users', {
                    headers: getHeaders()
                });
                
                if (response.status === 403) {
                    alert('您没有查看用户列表的权限');
                    return;
                }
                
                if (response.ok) {
                    const users = await response.json();
                    displayUsers(users);
                } else {
                    alert('获取用户列表失败');
                }
            } catch (error) {
                console.error('获取用户列表失败:', error);
                alert('获取用户列表失败');
            }
        }

        // 显示用户列表
        function displayUsers(users) {
            const content = document.getElementById('content');
            content.innerHTML = `
                <div class="d-flex justify-content-between align-items-center mb-3">
                    <h2>用户管理</h2>
                    <button class="btn btn-primary" onclick="showCreateUserModal()">创建用户</button>
                </div>
                <div class="table-responsive">
                    <table class="table">
                        <thead>
                            <tr>
                                <th>ID</th>
                                <th>用户名</th>
                                <th>邮箱</th>
                                <th>状态</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody>
                            ${users.content.map(user => `
                                <tr>
                                    <td>${user.id}</td>
                                    <td>${user.username}</td>
                                    <td>${user.email || ''}</td>
                                    <td>${user.enabled ? '<span class="badge bg-success">在线</span>' : '<span class="badge bg-danger">离线</span>'}</td>
                                    <td>
                                        <button class="btn btn-sm btn-primary" onclick="editUser(${user.id})">编辑</button>
                                        <button class="btn btn-sm btn-danger" onclick="deleteUser(${user.id})">删除</button>
                                        <button class="btn btn-sm btn-warning" onclick="forceLogout('${user.username}')">强制下线</button>
                                    </td>
                                </tr>
                            `).join('')}
                        </tbody>
                    </table>
                </div>
            `;
        }

        // 获取角色列表
        async function getAllRoles() {
            try {
                const response = await fetch('/api/roles', {
                    headers: getHeaders()
                });
                
                if (response.status === 403) {
                    alert('您没有查看角色列表的权限');
                    return;
                }
                
                if (response.ok) {
                    const roles = await response.json();
                    displayRoles(roles);
                } else {
                    alert('获取角色列表失败');
                }
            } catch (error) {
                console.error('获取角色列表失败:', error);
                alert('获取角色列表失败');
            }
        }

        // 显示角色列表
        function displayRoles(roles) {
            const content = document.getElementById('content');
            content.innerHTML = `
                <div class="d-flex justify-content-between align-items-center mb-3">
                    <h2>角色管理</h2>
                    <button class="btn btn-primary" onclick="showCreateRoleModal()">创建角色</button>
                </div>
                <div class="table-responsive">
                    <table class="table">
                        <thead>
                            <tr>
                                <th>ID</th>
                                <th>角色名称</th>
                                <th>描述</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody>
                            ${roles.content.map(role => `
                                <tr>
                                    <td>${role.id}</td>
                                    <td>${role.name}</td>
                                    <td>${role.description || ''}</td>
                                    <td>
                                        <button class="btn btn-sm btn-primary" onclick="editRole(${role.id})">编辑</button>
                                        <button class="btn btn-sm btn-danger" onclick="deleteRole(${role.id})">删除</button>
                                    </td>
                                </tr>
                            `).join('')}
                        </tbody>
                    </table>
                </div>
            `;
        }

        // 获取权限列表
        async function getAllPermissions() {
            try {
                const response = await fetch('/api/permissions', {
                    headers: getHeaders()
                });
                
                if (response.status === 403) {
                    alert('您没有查看权限列表的权限');
                    return;
                }
                
                if (response.ok) {
                    const permissions = await response.json();
                    displayPermissions(permissions);
                } else {
                    alert('获取权限列表失败');
                }
            } catch (error) {
                console.error('获取权限列表失败:', error);
                alert('获取权限列表失败');
            }
        }

        // 显示权限列表
        function displayPermissions(permissions) {
            const content = document.getElementById('content');
            content.innerHTML = `
                <div class="d-flex justify-content-between align-items-center mb-3">
                    <h2>权限管理</h2>
                    <button class="btn btn-primary" onclick="showCreatePermissionModal()">创建权限</button>
                </div>
                <div class="table-responsive">
                    <table class="table">
                        <thead>
                            <tr>
                                <th>ID</th>
                                <th>权限名称</th>
                                <th>描述</th>
                                <th>资源路径</th>
                                <th>操作类型</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody>
                            ${permissions.content.map(permission => `
                                <tr>
                                    <td>${permission.id}</td>
                                    <td>${permission.name}</td>
                                    <td>${permission.description || ''}</td>
                                    <td>${permission.resource}</td>
                                    <td>${permission.action}</td>
                                    <td>
                                        <button class="btn btn-sm btn-primary" onclick="editPermission(${permission.id})">编辑</button>
                                        <button class="btn btn-sm btn-danger" onclick="deletePermission(${permission.id})">删除</button>
                                    </td>
                                </tr>
                            `).join('')}
                        </tbody>
                    </table>
                </div>
            `;
        }

        // 编辑用户
        async function editUser(id) {
            try {
                const response = await fetch(`/api/users/${id}`, {
                    headers: getHeaders()
                });
                
                if (response.ok) {
                    const user = await response.json();
                    document.getElementById('editUserId').value = user.id;
                    document.getElementById('editUsername').value = user.username;
                    document.getElementById('editEmail').value = user.email || '';
                    document.getElementById('editPassword').value = '';
                    
                    // 获取所有角色并显示复选框
                    const rolesResponse = await fetch('/api/roles', {
                        headers: getHeaders()
                    });
                    if (rolesResponse.ok) {
                        const roles = await rolesResponse.json();
                        const rolesContainer = document.getElementById('editUserRoles');
                        rolesContainer.innerHTML = roles.content.map(role => `
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" value="${role.id}" 
                                    id="role${role.id}" ${user.roleIds && user.roleIds.includes(role.id) ? 'checked' : ''}>
                                <label class="form-check-label" for="role${role.id}">
                                    ${role.name}
                                </label>
                            </div>
                        `).join('');
                    }
                    
                    const modal = new bootstrap.Modal(document.getElementById('editUserModal'));
                    modal.show();
                }
            } catch (error) {
                console.error('获取用户信息失败:', error);
                alert('获取用户信息失败');
            }
        }

        // 保存用户
        async function saveUser() {
            const userId = document.getElementById('editUserId').value;
            const username = document.getElementById('editUsername').value;
            const email = document.getElementById('editEmail').value;
            const password = document.getElementById('editPassword').value;
            
            // 获取选中的角色
            const roleCheckboxes = document.querySelectorAll('#editUserRoles input[type="checkbox"]:checked');
            const roleIds = Array.from(roleCheckboxes).map(cb => parseInt(cb.value));
            
            const userData = {
                username,
                email,
                roleIds
            };
            
            if (password) {
                userData.password = password;
            }
            
            try {
                const url = userId ? `/api/users/${userId}` : '/api/users';
                const method = userId ? 'PUT' : 'POST';
                
                const response = await fetch(url, {
                    method: method,
                    headers: getHeaders(),
                    body: JSON.stringify(userData)
                });
                
                if (response.ok) {
                    const modal = bootstrap.Modal.getInstance(document.getElementById('editUserModal'));
                    modal.hide();
                    getAllUsers();
                } else {
                    alert('保存用户失败');
                }
            } catch (error) {
                console.error('保存用户失败:', error);
                alert('保存用户失败');
            }
        }

        // 删除用户
        async function deleteUser(id) {
            if (!confirm('确定要删除这个用户吗？')) {
                return;
            }
            
            try {
                const response = await fetch(`/api/users/${id}`, {
                    method: 'DELETE',
                    headers: getHeaders()
                });
                
                if (response.ok) {
                    getAllUsers();
                } else {
                    alert('删除用户失败');
                }
            } catch (error) {
                console.error('删除用户失败:', error);
                alert('删除用户失败');
            }
        }

        // 编辑角色
        async function editRole(id) {
            try {
                const response = await fetch(`/api/roles/${id}`, {
                    headers: getHeaders()
                });
                
                if (response.ok) {
                    const role = await response.json();
                    document.getElementById('editRoleId').value = role.id;
                    document.getElementById('editRoleName').value = role.name;
                    document.getElementById('editRoleDescription').value = role.description || '';
                    
                    // 获取所有权限并显示复选框
                    const permissionsResponse = await fetch('/api/permissions', {
                        headers: getHeaders()
                    });
                    if (permissionsResponse.ok) {
                        const permissions = await permissionsResponse.json();
                        const permissionsContainer = document.getElementById('editRolePermissions');
                        permissionsContainer.innerHTML = permissions.content.map(permission => `
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" value="${permission.id}" 
                                    id="permission${permission.id}" ${role.permissionIds && role.permissionIds.includes(permission.id) ? 'checked' : ''}>
                                <label class="form-check-label" for="permission${permission.id}">
                                    ${permission.name}
                                </label>
                            </div>
                        `).join('');
                    }
                    
                    const modal = new bootstrap.Modal(document.getElementById('editRoleModal'));
                    modal.show();
                }
            } catch (error) {
                console.error('获取角色信息失败:', error);
                alert('获取角色信息失败');
            }
        }

        // 保存角色
        async function saveRole() {
            const roleId = document.getElementById('editRoleId').value;
            const name = document.getElementById('editRoleName').value;
            const description = document.getElementById('editRoleDescription').value;
            
            // 获取选中的权限
            const permissionCheckboxes = document.querySelectorAll('#editRolePermissions input[type="checkbox"]:checked');
            const permissionIds = Array.from(permissionCheckboxes).map(cb => parseInt(cb.value));
            
            const roleData = {
                name,
                description,
                permissionIds
            };
            
            try {
                const url = roleId ? `/api/roles/${roleId}` : '/api/roles';
                const method = roleId ? 'PUT' : 'POST';
                
                const response = await fetch(url, {
                    method: method,
                    headers: getHeaders(),
                    body: JSON.stringify(roleData)
                });
                
                if (response.ok) {
                    const modal = bootstrap.Modal.getInstance(document.getElementById('editRoleModal'));
                    modal.hide();
                    getAllRoles();
                } else {
                    alert('保存角色失败');
                }
            } catch (error) {
                console.error('保存角色失败:', error);
                alert('保存角色失败');
            }
        }

        // 删除角色
        async function deleteRole(id) {
            if (!confirm('确定要删除这个角色吗？')) {
                return;
            }
            
            try {
                const response = await fetch(`/api/roles/${id}`, {
                    method: 'DELETE',
                    headers: getHeaders()
                });
                
                if (response.ok) {
                    getAllRoles();
                } else {
                    alert('删除角色失败');
                }
            } catch (error) {
                console.error('删除角色失败:', error);
                alert('删除角色失败');
            }
        }

        // 编辑权限
        async function editPermission(id) {
            try {
                const response = await fetch(`/api/permissions/${id}`, {
                    headers: getHeaders()
                });
                
                if (response.ok) {
                    const permission = await response.json();
                    document.getElementById('editPermissionId').value = permission.id;
                    document.getElementById('editPermissionName').value = permission.name;
                    document.getElementById('editPermissionDescription').value = permission.description || '';
                    document.getElementById('editPermissionResource').value = permission.resource;
                    document.getElementById('editPermissionAction').value = permission.action;
                    
                    const modal = new bootstrap.Modal(document.getElementById('editPermissionModal'));
                    modal.show();
                }
            } catch (error) {
                console.error('获取权限信息失败:', error);
                alert('获取权限信息失败');
            }
        }

        // 保存权限
        async function savePermission() {
            const permissionId = document.getElementById('editPermissionId').value;
            const name = document.getElementById('editPermissionName').value;
            const description = document.getElementById('editPermissionDescription').value;
            const resource = document.getElementById('editPermissionResource').value;
            const action = document.getElementById('editPermissionAction').value;
            
            const permissionData = {
                name,
                description,
                resource,
                action
            };
            
            try {
                const url = permissionId ? `/api/permissions/${permissionId}` : '/api/permissions';
                const method = permissionId ? 'PUT' : 'POST';
                
                const response = await fetch(url, {
                    method: method,
                    headers: getHeaders(),
                    body: JSON.stringify(permissionData)
                });
                
                if (response.ok) {
                    const modal = bootstrap.Modal.getInstance(document.getElementById('editPermissionModal'));
                    modal.hide();
                    getAllPermissions();
                } else {
                    alert('保存权限失败');
                }
            } catch (error) {
                console.error('保存权限失败:', error);
                alert('保存权限失败');
            }
        }

        // 删除权限
        async function deletePermission(id) {
            if (!confirm('确定要删除这个权限吗？')) {
                return;
            }
            
            try {
                const response = await fetch(`/api/permissions/${id}`, {
                    method: 'DELETE',
                    headers: getHeaders()
                });
                
                if (response.ok) {
                    getAllPermissions();
                } else {
                    alert('删除权限失败');
                }
            } catch (error) {
                console.error('删除权限失败:', error);
                alert('删除权限失败');
            }
        }

        // 显示创建用户模态框
        function showCreateUserModal() {
            document.getElementById('editUserId').value = '';
            document.getElementById('editUsername').value = '';
            document.getElementById('editEmail').value = '';
            document.getElementById('editPassword').value = '';
            document.getElementById('editUserRoles').innerHTML = '';
            
            // 获取所有角色并显示复选框
            fetch('/api/roles', {
                headers: getHeaders()
            })
            .then(response => response.json())
            .then(roles => {
                const rolesContainer = document.getElementById('editUserRoles');
                rolesContainer.innerHTML = roles.content.map(role => `
                    <div class="form-check">
                        <input class="form-check-input" type="checkbox" value="${role.id}" id="role${role.id}">
                        <label class="form-check-label" for="role${role.id}">
                            ${role.name}
                        </label>
                    </div>
                `).join('');
            })
            .catch(error => {
                console.error('获取角色列表失败:', error);
                alert('获取角色列表失败');
            });
            
            const modal = new bootstrap.Modal(document.getElementById('editUserModal'));
            modal.show();
        }

        // 显示创建角色模态框
        function showCreateRoleModal() {
            document.getElementById('editRoleId').value = '';
            document.getElementById('editRoleName').value = '';
            document.getElementById('editRoleDescription').value = '';
            document.getElementById('editRolePermissions').innerHTML = '';
            
            // 获取所有权限并显示复选框
            fetch('/api/permissions', {
                headers: getHeaders()
            })
            .then(response => response.json())
            .then(permissions => {
                const permissionsContainer = document.getElementById('editRolePermissions');
                permissionsContainer.innerHTML = permissions.content.map(permission => `
                    <div class="form-check">
                        <input class="form-check-input" type="checkbox" value="${permission.id}" id="permission${permission.id}">
                        <label class="form-check-label" for="permission${permission.id}">
                            ${permission.name} - ${permission.description}
                        </label>
                    </div>
                `).join('');
            })
            .catch(error => {
                console.error('获取权限列表失败:', error);
                alert('获取权限列表失败');
            });
            
            const modal = new bootstrap.Modal(document.getElementById('editRoleModal'));
            modal.show();
        }

        // 显示创建权限模态框
        function showCreatePermissionModal() {
            document.getElementById('editPermissionId').value = '';
            document.getElementById('editPermissionName').value = '';
            document.getElementById('editPermissionDescription').value = '';
            document.getElementById('editPermissionResource').value = '';
            document.getElementById('editPermissionAction').value = 'GET';
            
            const modal = new bootstrap.Modal(document.getElementById('editPermissionModal'));
            modal.show();
        }

        // 获取页面列表
        async function getAllPages() {
            try {
                const response = await fetch('/api/pages', {
                    headers: getHeaders()
                });
                
                if (response.status === 403) {
                    alert('您没有查看页面列表的权限');
                    return;
                }
                
                if (response.ok) {
                    const pages = await response.json();
                    displayPages(pages);
                } else {
                    alert('获取页面列表失败');
                }
            } catch (error) {
                console.error('获取页面列表失败:', error);
                alert('获取页面列表失败');
            }
        }

        // 显示页面列表
        function displayPages(pages) {
            const content = document.getElementById('content');
            content.innerHTML = `
                <div class="d-flex justify-content-between align-items-center mb-3">
                    <h2>页面管理</h2>
                    <button class="btn btn-primary" onclick="showCreatePageModal()">创建页面</button>
                </div>
                <div class="table-responsive">
                    <table class="table">
                        <thead>
                            <tr>
                                <th>ID</th>
                                <th>页面名称</th>
                                <th>路径</th>
                                <th>组件</th>
                                <th>图标</th>
                                <th>排序</th>
                                <th>父页面</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody>
                            ${pages.content.map(page => `
                                <tr>
                                    <td>${page.id}</td>
                                    <td>${page.name}</td>
                                    <td>${page.path}</td>
                                    <td>${page.component}</td>
                                    <td>${page.icon || ''}</td>
                                    <td>${page.sort}</td>
                                    <td>${page.parentId || '无'}</td>
                                    <td>
                                        <button class="btn btn-sm btn-primary" onclick="editPage(${page.id})">编辑</button>
                                        <button class="btn btn-sm btn-danger" onclick="deletePage(${page.id})">删除</button>
                                    </td>
                                </tr>
                            `).join('')}
                        </tbody>
                    </table>
                </div>
            `;
        }

        // 编辑页面
        async function editPage(id) {
            try {
                const response = await fetch(`/api/pages/${id}`, {
                    headers: getHeaders()
                });
                
                if (response.ok) {
                    const page = await response.json();
                    document.getElementById('editPageId').value = page.id;
                    document.getElementById('editPageName').value = page.name;
                    document.getElementById('editPagePath').value = page.path;
                    document.getElementById('editPageComponent').value = page.component;
                    document.getElementById('editPageIcon').value = page.icon || '';
                    document.getElementById('editPageSort').value = page.sort || 0;
                    
                    // 获取所有页面作为父页面选项
                    const pagesResponse = await fetch('/api/pages', {
                        headers: getHeaders()
                    });
                    if (pagesResponse.ok) {
                        const pages = await pagesResponse.json();
                        const parentSelect = document.getElementById('editPageParentId');
                        parentSelect.innerHTML = '<option value="">无</option>' + 
                            pages.content
                                .filter(p => p.id !== page.id) // 排除当前页面
                                .map(p => `
                                    <option value="${p.id}" ${page.parentId === p.id ? 'selected' : ''}>
                                        ${p.name}
                                    </option>
                                `).join('');
                    }
                    
                    const modal = new bootstrap.Modal(document.getElementById('editPageModal'));
                    modal.show();
                }
            } catch (error) {
                console.error('获取页面信息失败:', error);
                alert('获取页面信息失败');
            }
        }

        // 保存页面
        async function savePage() {
            const pageId = document.getElementById('editPageId').value;
            const name = document.getElementById('editPageName').value;
            const path = document.getElementById('editPagePath').value;
            const component = document.getElementById('editPageComponent').value;
            const icon = document.getElementById('editPageIcon').value;
            const sort = parseInt(document.getElementById('editPageSort').value) || 0;
            const parentId = document.getElementById('editPageParentId').value;
            
            const pageData = {
                name,
                path,
                component,
                icon,
                sort,
                parentId: parentId || null
            };
            
            try {
                const url = pageId ? `/api/pages/${pageId}` : '/api/pages';
                const method = pageId ? 'PUT' : 'POST';
                
                const response = await fetch(url, {
                    method: method,
                    headers: getHeaders(),
                    body: JSON.stringify(pageData)
                });
                
                if (response.ok) {
                    const modal = bootstrap.Modal.getInstance(document.getElementById('editPageModal'));
                    modal.hide();
                    getAllPages();
                } else {
                    alert('保存页面失败');
                }
            } catch (error) {
                console.error('保存页面失败:', error);
                alert('保存页面失败');
            }
        }

        // 删除页面
        async function deletePage(id) {
            if (!confirm('确定要删除这个页面吗？')) {
                return;
            }
            
            try {
                const response = await fetch(`/api/pages/${id}`, {
                    method: 'DELETE',
                    headers: getHeaders()
                });
                
                if (response.ok) {
                    getAllPages();
                } else {
                    alert('删除页面失败');
                }
            } catch (error) {
                console.error('删除页面失败:', error);
                alert('删除页面失败');
            }
        }

        // 显示创建页面模态框
        function showCreatePageModal() {
            document.getElementById('editPageId').value = '';
            document.getElementById('editPageName').value = '';
            document.getElementById('editPagePath').value = '';
            document.getElementById('editPageComponent').value = '';
            document.getElementById('editPageIcon').value = '';
            document.getElementById('editPageSort').value = '0';
            document.getElementById('editPageParentId').innerHTML = '<option value="">无</option>';
            
            // 获取所有页面作为父页面选项
            fetch('/api/pages', {
                headers: getHeaders()
            })
            .then(response => response.json())
            .then(pages => {
                const parentSelect = document.getElementById('editPageParentId');
                parentSelect.innerHTML = '<option value="">无</option>' + 
                    pages.content.map(page => `
                        <option value="${page.id}">${page.name}</option>
                    `).join('');
            })
            .catch(error => {
                console.error('获取页面列表失败:', error);
                alert('获取页面列表失败');
            });
            
            const modal = new bootstrap.Modal(document.getElementById('editPageModal'));
            modal.show();
        }

        // 强制下线用户
        async function forceLogout(username) {
            if (!confirm(`确定要强制用户 ${username} 下线吗？`)) {
                return;
            }
            
            try {
                const response = await fetch(`/api/auth/force-logout/${username}`, {
                    method: 'POST',
                    headers: getHeaders()
                });
                
                if (response.ok) {
                    alert(`用户 ${username} 已被强制下线`);
                    // 刷新用户列表
                    getAllUsers();
                } else {
                    alert('强制下线失败');
                }
            } catch (error) {
                console.error('强制下线失败:', error);
                alert('强制下线失败');
            }
        }

        // 退出登录
        async function logout() {
            try {
                const response = await fetch('/api/auth/logout', {
                    method: 'POST',
                    headers: getHeaders()
                });
                
                if (response.ok) {
                    localStorage.removeItem('token');
                    window.location.href = '/login';
                }
            } catch (error) {
                console.error('退出登录失败:', error);
            }
        }
    </script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html> 